<?php

namespace App\Models\Applet\Cart;


use App\Helpers\MvcHelper;

class CartModel extends BaseCartModel
{
    protected $table = 'carts';

    const TYPE_SPONSOR = 10; // 认养商品
    const TYPE_SHOP    = 20; // 商品

    /**
     * 总条数
     * @param int $type
     * @return int
     */
    public function total(int $type): int
    {
        return $this->where('type', $type)
                    ->where('user_id', MvcHelper::getLoginUserId())
                    ->where('deleted', self::DELETED_NO)
                    ->count();
    }

    /**
     * 购物车列表
     *
     * @param int $type
     * @param array $fields
     * @return array
     */
    public function list(int $type, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        return $this->select($fields)
                    ->where('type', $type)
                    ->where('user_id', MvcHelper::getLoginUserId())
                    ->orderBy('id', 'desc')
                    ->where('deleted', self::DELETED_NO)
                    ->offset((CURRENT_PAGE - 1) * PAGE_SIZE)
                    ->limit(PAGE_SIZE)
                    ->get()
                    ->toArray();
    }

    /**
     * 根据购物车用户id和ids获取数据
     * @param int $userId
     * @param array $ids
     * @param array $fields
     * @return array
     */
    public function getItemsByUserIdAndIds(int $userId, array $ids, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        return $this->select($fields)
                    ->where('user_id', $userId)
                    ->whereIn('id', $ids)
                    ->where('deleted', self::DELETED_NO)
                    ->get()
                    ->toArray();
    }

    /**
     * 根据商品id获取数据
     * @return void
     */
    public function getItemByGoodsIdAndType(int $goodsId, int $type, array $fields = self::QUERY_DEFAULT_FIELDS): array
    {
        $result = $this->select($fields)
                       ->where('user_id', MvcHelper::getLoginUserId())
                       ->where('goods_id', $goodsId)
                       ->where('type', $type)
                       ->where('deleted', self::DELETED_NO)
                       ->first();
        return $result ? $result->toArray() : [];
    }
}
